<template>
	<view>
		<uni-nav-bar fixed="true" backgroundColor="#f5f5f5" height="120rpx" @clickLeft="back" statusBar="true">
			<view slot="left">
				<uni-icons type="back" size="30"></uni-icons>
			</view>
			<view slot="right">
				<view class="isPost" @click="check">
					发布
				</view>
			</view>
		</uni-nav-bar>
		<u-modal :show="isPost" title="温馨提示" content="是否要发布帖子?" width="500rpx" @confirm="postControll"
			@cancel="isPost = false" showCancelButton>
		</u-modal>
		<view class="body">
			<u-input :class="{'title':true,'buleBottom':color,'greyBottom':!color}" type="text" placeholder="标题(必填)"
				border="none" v-model="p.title" maxlength="30" @blur="color = false" @focus="color = true;emo = false"
				:showWordLimit="true" fontSize="40rpx">
			</u-input>
			<u-cell-group :border="false">
				<u-cell isLink @click="changeType">
					<view slot="title" class="select">
						发布板块
					</view>
					<view slot="value" class="type" v-if="p.type!==-1">
						{{postTypes[0][p.type].name}}
					</view>
				</u-cell>
			</u-cell-group>
			<u-picker :show="selectType" :columns="postTypes" keyName="name" @cancel="selectType = false"
				@confirm="chooseType"></u-picker>
			<view class="top">
			</view>
			<editor :style="{'height':editHeight+'px'}" placeholder="请尽情发挥吧..." class="edit" id="editor"
				@ready="onEditorReady" @focus="emo = false">
			</editor>
			<view class="padding">
			</view>
			<view class="footer">
				<view class="bar">
					<uni-icons type="image" size="40" @click="selectImg" class="icon"></uni-icons>
					<uni-icons customPrefix="iconfont" type="icon-smile" size="40" @click="emo = !emo" class="icon">
					</uni-icons>
					<uni-icons type="videocam" size="40" @click="isUpdateVideo = true" class="icon"></uni-icons>
					<uni-icons customPrefix="iconfont" type="icon-sami-select" size="40" @click="divider" class="icon">
					</uni-icons>
					<uni-icons type="undo" size="40" @click="undo" class="icon"></uni-icons>
					<uni-icons type="redo" size="40" @click="redo" class="icon"></uni-icons>
				</view>
				<u-transition :show="emo" mode="fade-up">
					<view class="drawer" v-if="emo">
						<view class="emotion" v-if="emo">
							<swiper :indicator-dots="true" class="swiper">
								<swiper-item v-for="(parentItem, parentIndex) in emoList" :key="parentIndex">
									<view class="swiper-item">
										<image v-for="item in parentItem" :src="item.value | imgSrc" :key="item.value"
											class="image" @click="clickEmoji(item)" mode="aspectFit"></image>
									</view>
								</swiper-item>
							</swiper>
						</view>
					</view>
				</u-transition>
			</view>
		</view>
		<hqs-popup title="上传视频" :value="isUpdateVideo" @close="isUpdateVideo = false">
			<view class="body">
				<image v-if="video.image!=''" :src="video.image" class="zhan" mode="aspectFit"
					@click="selectVideoFront">
				</image>
				<canvas canvas-id="myCanvas" class="canvas"></canvas>
				<button class="bgroup" :type="video.image == ''?'primary':'success'" @click="selectVideoFront"><text
						v-if="video.image!=''">封面已上传</text><text v-else>上传封面</text></button>
				<button class="bgroup" :type="video.src == ''?'primary':'success'" @click="selectVideo"><text
						v-if="video.src!=''">视频已上传</text><text v-else>上传视频</text></button>
				<button class="bgroup" type="primary" :disabled="video.src==''||video.image==''"
					@click="insertVideo">确认</button>
				<view style="padding: 20rpx;"></view>
			</view>
		</hqs-popup>
	</view>
</template>

<script>
	import pop from "@/components/hqs-popup/hqs-popup.vue"
	import util from "@/config/util.js"
	import config from "@/config/config.js"
	export default {
		components: {
			pop
		},
		data() {
			return {
				reEdit: false, //是否为再编辑
				isUpdateVideo: false,
				isPost: false,
				color: false,
				selectType: false,
				editHeight: 800, //edit高度
				emo: false, //表情栏
				p: {
					title: "",
					html: "",
					text: "",
					image: "",
					type: -1,
				},
				front: false,
				video: {
					image: "",
					src: "",
				},
				emoList: util.emoList,
				postTypes: [config.postTypes]
			}
		},
		methods: {
			check() {
				if (this.p.title == "") {
					uni.showToast({
						icon: "none",
						title: "请填写标题!"
					});
					return;
				}
				if (this.p.type == -1) {
					uni.showToast({
						icon: "none",
						title: "请选择分区!"
					});
					return;
				}
				this.isPost = true
			},
			changeType() {
				if (this.reEdit) {
					uni.showToast({
						icon: "none",
						title: "暂不支持再编辑修改分区!"
					});
					return;
				}
				this.selectType = true
			},
			chooseType(e) {
				console.log(e.indexs[0])
				this.p.type = e.indexs[0]
				this.selectType = false
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
					if (this.reEdit) {
						this.editorCtx.setContents({
							html: this.p.html
						})
					}
				}).exec()
			},
			insertImg(url) {
				let self = this
				this.editorCtx.insertImage({
					src: url,
					width: '90%',
					mode: 'widthFix',
					data: {
						'type': 'image'
					},
					success() {
						self.insertN()
					}
				})
			},
			insertVideo() {
				if (this.video.src == '' || this.video.image == '') {
					uni.showToast({
						icon: 'none',
						title: "请上传视频以及视频封面!"
					});
					return;
				}
				let self = this
				this.editorCtx.insertImage({
					src: this.video.image,
					width: '100%',
					mode: 'widthFix',
					data: {
						'type': 'video',
						'src': this.video.src
					},
					success() {
						self.video.src = '',
							self.video.image = '',
							self.isUpdateVideo = false,
							self.insertN()
					}
				})

			},
			scrollIntoView() {
				this.editorCtx.scrollIntoView()
			},
			insertN() {
				let self = this
				this.editorCtx.insertText({
					text: "\n",
					success() {
						setTimeout(() => {
							self.scrollIntoView()
						}, 200)
					}
				})
			},
			clickEmoji(item) {
				// console.log(item);
				let url = `../../static/emoji/d_${item.value}.gif`
				this.insertEmo(url)
			},
			insertEmo(url) {
				this.editorCtx.insertImage({
					src: url,
					width: "30px",
					mode: "widthFix"
				})
			},
			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},
			divider() {
				this.editorCtx.insertDivider()
			},
			postControll() {
				if (this.reEdit) {
					this.edit()
				} else {
					this.post()
				}
			},
			edit() {
				// console.log("edit")
				this.editorCtx.getContents({
					success: (data) => {
						this.p.image = JSON.stringify(this.httpString(data.html))
						this.p.html = data.html
						this.p.text = data.text
						delete this.p.date
						this.$request.TokenRequest({
							url: "/post/ReEditPost"
						}, this.p).then(res => {
							if (res.state === 200) {
								uni.showToast({
									icon: "success",
									title: "发布成功!"
								})
								uni.redirectTo({
									url: "../post/post?pid=" + res.data.pid
								})
							} else {
								uni.showToast({
									icon: "none",
									title: res.message
								})
							}
						})
					}
				})
			},
			post() {
				// console.log("发布");
				this.editorCtx.getContents({
					success: (data) => {
						// console.log(data)
						this.p.image = JSON.stringify(this.httpString(data.html))
						this.p.html = data.html
						this.p.text = data.text
						this.$request.TokenRequest({
							url: "/post/PublishPost"
						}, this.p).then(res => {
							if (res.state === 200) {
								uni.showToast({
									icon: "success",
									title: "发布成功!"
								})
								uni.redirectTo({
									url: "../post/post?pid=" + res.data.pid
								})
							} else {
								uni.showToast({
									icon: "none",
									title: res.message
								})
							}
						})
					}
				})
			},
			selectImg() {
				let self = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success(res) {
						// console.log(JSON.stringify(res.tempFilePaths))
						self.uploadImg(res.tempFilePaths[0])
					}
				})
			},
			selectVideoFront() {
				let self = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success(res) {
						let that = self
						// console.log(JSON.stringify(res.tempFilePaths))
						uni.showLoading({
							mask: true,
							title: '上传中...'
						})
						self.addWaterMark(res.tempFilePaths[0], (path) => {
							that.uploadVideoFront(path)
						})

					}
				})
			},
			// 添加水印
			addWaterMark(src, callback) {
				let self = this
				uni.getImageInfo({
					src: src,
					fail(err) {
						console.log(err)
					},
					success: res => {
						let data = "▶"; /** 作为水印 */
						console.log(res)
						let ctx = uni.createCanvasContext('myCanvas'); /** 创建画布 */
						let textToWidth = 130; /**这里设置的是水印位置*/
						let textToHeight = 85;
						//将图片src放到cancas内，宽高为图片大小
						// console.log(src)
						ctx.drawImage(src, 0, 0, 300, 225)
						//将声明的时间放入canvas
						ctx.setFontSize(40) //注意：设置文字大小必须放在填充文字之前，否则不生效
						ctx.setFillStyle("rgba(0,0,0,0.5)");
						ctx.fillText(data, textToWidth, textToHeight) //水印内容，位置
						// 开始绘制添加水印的图片并显示在页面中
						ctx.draw(false, () => {
							setTimeout(() => {
								console.log("draw");
								uni.canvasToTempFilePath({
									canvasId: "myCanvas",
									success: ress => {
										console.log(ress.tempFilePath)
										callback(ress.tempFilePath);
									}
								})
							}, 500)
						})
					}
				})
			},
			selectVideo() {
				let self = this
				uni.chooseVideo({
					sourceType: ['album'],
					extension: ['mp4'],
					compressed: false,
					success(res) {
						uni.showLoading({
							mask: true,
							title: "视频上传中..."
						})
						self.uploadVideo(res.tempFilePath)
					}
				})
			},
			uploadVideoFront(path) {
				this.$util.uploadFile(path).then(res => {
					this.video.image = res
					uni.hideLoading()
				}).catch(err => {
					uni.showToast({
						icon: "error",
						title: "视频封面上传失败!"
					})
				})
			},
			uploadVideo(path) {
				this.$util.uploadFile(path).then(res => {
					this.video.src = res
					uni.hideLoading()
				}).catch(err => {
					uni.showToast({
						icon: "error",
						title: "视频上传失败!"
					})
				})
			},
			uploadImg(imgpath) {
				this.$util.uploadFile(imgpath).then(res => {
					this.insertImg(res);
				}).catch(err => {
					uni.showToast({
						icon: 'error',
						title: "图片上传失败!"
					})
				})
			},
			back() {
				uni.navigateBack({})
			},
			// scroll() {
			// 	console.log("滑到底部")
			// 	this.$nextTick(function() {
			// 		uni.pageScrollTo({
			// 			scrollTop: 2000000,
			// 			duration: 200
			// 		})
			// 	})
			// },
			//修改editor高度
			resize() {
				console.log('resize')
				let self = this
				let top = uni.createSelectorQuery().select(".top")
				let footer = uni.createSelectorQuery().select(".footer")
				top.boundingClientRect(t => {
					footer.boundingClientRect(f => {
						// console.log(t.bottom);
						// console.log(f.top);
						self.editHeight = f.top - t.bottom - 60
						setTimeout(() => {
							self.scrollIntoView()
						}, 200)
						// console.log(this.editHeight)
					}).exec()
				}).exec()
			},
			httpString(s) {
				var reg = /(https?|http):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
				var reg1 = /<img src="(.*?)"/g;
				s = s.match(reg1);
				if (s == null) return []
				s = s.join()
				s = s.match(reg)
				console.log(s)
				return (s)
			},
		},
		onReady() {
			setTimeout(() => {
				this.resize()
			}, 300)

		},
		onBackPress() {
			uni.offKeyboardHeightChange(() => {})
		},
		mounted() {

		},
		onLoad(option) {
			console.log(option)
			if (option.load === "true") {
				this.reEdit = true
				this.p = JSON.parse(option.post)
			}
			let self = this
			uni.onKeyboardHeightChange((e) => {
				setTimeout(() => {
					self.resize()
				}, 300)

			})
		},
		filters: {
			imgSrc(value) {
				return `../../static/emoji/d_${value}.gif`
			}
		},
	}
</script>

<style lang="scss" scoped>
	.isPost {
		background-color: #42A5F5;
		color: #FFFFFF;
		font-size: 30rpx;
		padding: 5rpx 18rpx;
		border-radius: 10rpx;
	}

	.zhan {
		width: 100%;
	}

	.canvas {
		position: absolute;
		visibility: hidden;
	}

	.body {
		width: 90%;
		margin: 0 auto;
	}

	/deep/ .input-placeholder {
		font-size: 40rpx;
	}

	.title {
		height: 100rpx;
		border-radius: 0;
	}

	.greyBottom {
		border-bottom: 5rpx solid #C1C5CD;
	}

	.buleBottom {
		border-bottom: 5rpx solid #42A5F5;
	}

	.select {
		display: flex;
		align-items: center;
		font-size: 30rpx;
		color: #C1C5CD;
		line-height: 60rpx;
	}

	.type {
		font-size: 40rpx;
		margin-right: 20rpx;
		font-weight: bold;
		color: #333333;
	}

	.top {
		margin-top: 40rpx;
	}

	.edit {
		// margin-top: 40rpx;
		// background: #42A5F5;
	}

	.padding {
		padding-top: 60px;
	}

	.bgroup {
		margin: 50rpx 0;
	}

	.footer {
		border-top: 1rpx solid #C1C5CD;
		margin: 6rpx auto;
		background-color: #FFFFFF;
		position: absolute;
		width: 90%;
		bottom: 0;

		.icon {
			padding: 12rpx 15rpx;
		}

		.bar {
			display: flex;
			align-items: center;
		}

		.drawer {
			display: block;
			width: 100%;
			height: 420rpx;

			.image {
				width: 55rpx;
				height: 55rpx;
				padding: 15rpx;
				margin: 10rpx 0;
			}

			.emotion {
				text-align: center;
				height: 100%;

				.swiper {
					height: 100%;
				}
			}
		}
	}
</style>
